package com.shenjun.bank.handler;

import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.ChannelInboundHandler;
import io.netty.channel.ChannelInboundHandlerAdapter;
import io.netty.channel.ChannelInitializer;
import io.netty.channel.socket.nio.NioSocketChannel;
import io.netty.handler.logging.LogLevel;
import io.netty.handler.logging.LoggingHandler;
import io.netty.handler.timeout.IdleStateEvent;
import io.netty.handler.timeout.IdleStateHandler;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;

import java.util.concurrent.TimeUnit;

@Slf4j
@Component
public class HeartbeatHandler extends ChannelInitializer<NioSocketChannel> {


    @Override
    protected void initChannel(NioSocketChannel channel) throws Exception {
        log.info("8001服务器心跳检测连接建立。。。");
        channel.pipeline().addLast(new LoggingHandler(LogLevel.DEBUG));
        /*
         * long readerIdleTime 表示多久没有读数据了，就会发送心跳检测包检测连接
         * long writerIdleTime 表示多久没有写数据了，就会发送心跳检测包检测连接
         * long allIdleTime 表示多久没有读写数据了，就会发送心跳检测包检测连接
         *
         * IdleStateHandler触发后，就会传递给一下个handler处理，下一个handler的userEventTiggered处理
         * */
        channel.pipeline().addLast(new IdleStateHandler(3,5,7, TimeUnit.SECONDS));
        channel.pipeline().addLast(new ChannelInboundHandlerAdapter() {
            @Override
            public void userEventTriggered(ChannelHandlerContext ctx, Object evt) throws Exception {
                super.userEventTriggered(ctx, evt);
                if (evt instanceof IdleStateEvent) {
                    IdleStateEvent evt1 = (IdleStateEvent) evt;
                    String eventType = null;
                    switch (evt1.state()) {
                        case READER_IDLE:
                            eventType = "读空闲";
                            break;
                        case WRITER_IDLE:
                            eventType = "写空闲";
                            break;
                        case ALL_IDLE:
                            eventType = "读写空闲";
                            break;
                    }
                    log.info("客户端：[{}],---[{}]---", channel.remoteAddress(), eventType);
                }
            }
        });
    }
}
